package cn.uncode.rpc.core;

import cn.uncode.rpc.common.log.Logger;
import cn.uncode.rpc.common.log.LoggerFactory;
import cn.uncode.rpc.common.message.Messages;
import cn.uncode.rpc.exception.FrameworkException;

public abstract class AbstractNode implements Node {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(AbstractNode.class);
	
	protected URL url;
	
	protected volatile boolean init = false;
	protected volatile boolean available = false;
	
	public AbstractNode(URL url){
		this.url = url;
	}

	@Override
	public synchronized void init() {
		if (init) {
			LOGGER.warn(this.getClass().getSimpleName() + " node already init: " + desc());
            return;
        }
		
		boolean result = doInit();

        if (!result) {
        	LOGGER.error(this.getClass().getSimpleName() + " node init Error: " + desc());
            throw new FrameworkException(Messages.getString("RuntimeError.NodeInitError", this.getClass().getSimpleName(), desc()));
        } else {
        	LOGGER.info(this.getClass().getSimpleName() + " node init Success: " + desc());

            init = true;
            available = true;
        }

	}
	
	protected abstract boolean doInit();

	@Override
	public boolean isAvailable() {
		return available;
	}
	
    public void setAvailable(boolean available) {
        this.available = available;
    }

	@Override
	public URL getUrl() {
		return url;
	}
	
	@Override
    public String desc() {
        return "[" + this.getClass().getSimpleName() + "] url=" + url;
    }

}
